package com.zbs.framework.common.weixin;

import com.zbs.framework.common.utils.ErrorAssert;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description:
 * @author: Zbs
 * @create: 2020-10-23 13:08
 */
@Component
@Slf4j
public class WxMsgPush {

    @Autowired
    private  WxMpService myWxMpService;

    /**
     * 发送微信模板信息
     *
     * @param openId 接受者openId
     */
    public void sendWxMsg(String openId, String templateId, String url, List<WxTemplateData> dataList) {
        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(openId)
                // 模板id
                .templateId(templateId)
                // 模板跳转链接
                .url(url)
                .build();
        // 添加模板数据
        if (!CollectionUtils.isEmpty(dataList)){
            dataList.forEach(data -> templateMessage.addData(new WxMpTemplateData(data.getName(), data.getValue(), data.getColor())));
        }else {
            ErrorAssert.error("数据不能为空");
        }

        String msgId = null;
        try {
            // 发送模板消息
            msgId = myWxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        log.warn("·==++--·推送微信模板信息：{}·--++==·", msgId != null ? "成功" : "失败");
    }

}




